package com.acme.bankapp.services.email;

import java.util.LinkedList;
import java.util.List;


/**
 * Email Sender class
 * 
 */
public class EmailService {

	private List<Email> emails = new LinkedList<Email>();

	private EmailSender sender;

	public EmailService() {
		sender = new EmailSender();
		sender.start();
	}

	/**
	 * Add email to sending list.
	 * 
	 * @param email
	 */
	public void addEmailToSendingList(Email email) {
		synchronized (emails) {
			emails.add(email);
			emails.notifyAll();
		}

	}

	/**
	 * Close service. All emails from queue will be send
	 */
	public void closeService() {
		synchronized (emails) {
			emails.notifyAll();
		}
		sender.interrupt();
	}
	
	/**
	 * Possible long operation...
	 * @param email
	 */
	private void sendEmail(Email email){
		System.out.println("EmailSended\n" + email);
	}

	class EmailSender extends Thread {
		@Override
		public void run() {

			while (true) {
				Email email;
				synchronized (emails) {

					while (emails.isEmpty()) {
						if (isInterrupted())
							return;
						try {
							emails.wait();
						} catch (InterruptedException e) {
							System.err
									.println("Email service was interrupted!");
							if (emails.isEmpty())
								return;
						}
					}
					email = emails.remove(0);
				}
				sendEmail(email);
			}

		}
	}

}
